#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
#include <vector>
using namespace std;
#include "ServerSocket.h"
#include "SocketException.h"
#include "Node.h"
#include "Load_data.h"
#include "Search.h"
#include "Sort.h"

#define TIMES 10000 //定期重新排序标签
#define DEBUG 0

int main ( int argc, char **argv ) {
    /////////////////导入标签数据
    PNODE tree=new NODE;
    tree->name="字典库";
    const char *path="/usr/local/segment_word/dict_20120710";
    List(path, tree);
    tree->tag_continue=0;

    sort_tree(tree);
    update_dic(tree);


    /////////////////定期重新整理数据
    unsigned int times=0;

    ////////////////开启socket服务
    try {
        // Create the socket
        ServerSocket server ( 30000 );
        while ( true ) {
            ServerSocket new_sock;
            server.accept ( new_sock );
            try {
                while ( true ) {
                    string data;
                    new_sock >> data;
#if DEBUG
                    cout<<"input:"<<data<<endl;
#endif
                    data=search_tree(tree,data.c_str());//分出标签

                    if (times==TIMES) { //重新排序标签
                        sort_tree(tree);
   			update_dic(tree);
                        times=0;
                        }
                    if (data.length()==0) data="error";
                    else ++times;
#if DEBUG
                    cout<<"output:"<<data<<endl<<endl;
#endif
                    new_sock << data;
                    }
                }
            catch ( SocketException& ) {}

            }
        }
    catch ( SocketException& e ) {
        cout << "Exception was caught:" << e.description() << "\nExiting.\n";
        }

    return 0;
    }
